package com.chineseall.rebirth.bridge.aspect;

import javax.servlet.http.HttpServletRequest;

import jmind.core.annotation.Validation;
import jmind.core.aspect.JoinPoints;
import jmind.core.spring.AbstractController;
import jmind.core.util.RequestUtil;
import jmind.resource.manager.ZKMongoManager;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.chineseall.rebirth.api.helper.Const;
import com.chineseall.rebirth.api.helper.LoginHelper;
import com.chineseall.rebirth.api.pojo.LoginUser;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Component
@Aspect
public class ValidationAspect {

    private DBCollection coll = ZKMongoManager.getInstance().getResource("stat").getCollection("UserAuth");

    @Pointcut("@annotation(jmind.core.annotation.Validation)")
    public void exe2() {
    }

    @Around("exe2()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        return doit(pjp);
    }

    private Object doit(ProceedingJoinPoint pjp) throws Throwable {
        final Validation m = JoinPoints.getAnnotation(pjp, Validation.class);
        HttpServletRequest request = JoinPoints.findRequest(pjp);
        // 是否登录
        LoginUser user = LoginHelper.getLoginUser(request);
        if (user == null) {
            return AbstractController.REDIRECT + Const.LOGIN_URL + RequestUtil.getURL(request);
        }
        if (m.id() > 0) { // 走权限认证
            BasicDBObject o = new BasicDBObject("_id", String.valueOf(user.getUid()));
            o.put("a", m.id());

            //  System.out.println(m.id() + "----" + user.getUid());

            DBObject one = coll.findOne(o);
            if (one != null) {
                Object obj = pjp.proceed();
                return obj;
            }
        } else {
            return pjp.proceed();
        }

        request.setAttribute(AbstractController.MESSAGE, "没权限");
        return m.back();

    }
}
